//
//  LCSignViewController.swift
//  mggz
//
//  Created by QinWei on 2018/1/5.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import SVProgressHUD
import MJRefresh
import ObjectMapper
class LCSignViewController: UIViewController {
    lazy var itemArray : [MWCurrentLocationModel] = [MWCurrentLocationModel]()
    
    var greenArray:[MWCurrentLocationModel] = [MWCurrentLocationModel]()
    var redArray:[MWCurrentLocationModel] = [MWCurrentLocationModel]()
    var greyArray:[MWCurrentLocationModel] = [MWCurrentLocationModel]()
    
     var selectedProject : LCProjectListModel?
     var signCount:((Int) -> Void)? = nil
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var emptylayout: UIView!
    @IBOutlet weak var emptylabel: UILabel!
    lazy var itemPoint = [CLLocationCoordinate2D]()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.init(red: 0.91, green: 0.91, blue: 0.91, alpha: 1);
        self.tableView.delegate = self
        self.tableView.dataSource = self
        
        self.tableView.register(UINib.init(nibName: "LCSignCell", bundle: nil), forCellReuseIdentifier: "sign")
        //self.tableView.separatorInset = UIEdgeInsetsMake(5, 10, 0, 10)
        self.tableView.separatorInset = UIEdgeInsets.zero
        self.tableView.tableFooterView = UIView(frame: CGRect.zero)
        self.tableView.separatorStyle = .singleLine
        self.tableView.separatorColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        
        var tableHeader = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(setupMWLocationData))
        tableHeader?.stateLabel.isHidden = true
        self.tableView.mj_header = tableHeader
        
        self.addNotificationObserve()
    }
    private func addNotificationObserve(){
        let noficationName = Notification.Name.init(LCMainProjectNotification)
        NotificationCenter.default.addObserver(self, selector: #selector(getMWLocationData(notification:)), name: noficationName, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(getPositionlist(notification:)), name: Notification.Name.init(GuiJiPointList), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(getPositionlist(notification:)), name: Notification.Name.init(MDCQListNotification), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(getRefreshData(notification:)), name: Notification.Name.init(MGQDListNotification), object: nil)
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    @objc func getMWLocationData(notification:Notification) {
        let userInfo = notification.userInfo as! [String:AnyObject]
        self.selectedProject = userInfo["project"] as? LCProjectListModel
        //self.setupMWLocationData()
        self.refreshRequest()
    }
    
    @objc func getPositionlist(notification:Notification){
        self.itemPoint.removeAll()
        if notification.object is [CLLocationCoordinate2D]{
            self.itemPoint.append(contentsOf: (notification.object as! [CLLocationCoordinate2D]))
        }
        //BMKPolygonContainsCoordinate(<#T##point: CLLocationCoordinate2D##CLLocationCoordinate2D#>, <#T##polygon: UnsafeMutablePointer<CLLocationCoordinate2D>!##UnsafeMutablePointer<CLLocationCoordinate2D>!#>, <#T##count: UInt##UInt#>)
        
        //print("\((notification.object as! [CLLocationCoordinate2D]).count)")
    }
    
    @objc func getRefreshData(notification:Notification){
        self.refreshRequest()
    }
    
    func refreshRequest(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            self.tableView.mj_header.endRefreshing()
            return
        }
        //QWTextWithStatusHud("正在加载...", target: self.view)
        SVProgressHUD.show(withStatus: "正在加载")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.clear)
        LCAPiMainManager.request(.GetMWLotion(start: "0", limit: "1000", sql: "SignedResult >=0", sqlParam: "{}", supplybaseid: (selectedProject?.MarketSupplyBaseID)!, AccountId: accountId)) { (result) in
            SVProgressHUD.dismiss()
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                print(jsonString)
                if let resultDic = jsonString["Result"] as? [String: AnyObject] {
                    
                    if let itemDic = resultDic["Items"] as? [[String: Any]] {
                        self.itemArray.removeAll()
                        /*var greenArray:[MWCurrentLocationModel] = [MWCurrentLocationModel]()
                        var redArray:[MWCurrentLocationModel] = [MWCurrentLocationModel]()
                        var greyArray:[MWCurrentLocationModel] = [MWCurrentLocationModel]()*/
                        self.greenArray.removeAll()
                        self.redArray.removeAll()
                        self.greyArray.removeAll()
                        
                        var resultArray: [MWCurrentLocationModel] = Mapper<MWCurrentLocationModel>().mapArray(JSONArray: itemDic)
                        
                        for item in resultArray{
                            if (item.SignedResult?.rawValue ?? 0) == -1{
                                
                            }else if (item.SignedResult?.rawValue ?? 0) == 0{
                                
                                if item.IsOnline! {
                                    var longitude = item.Location?.object(forKey: "Longitude") as? NSString
                                    var latitude = item.Location?.object(forKey: "Latitude") as? NSString
                                    var flag = BMKPolygonContainsCoordinate(CLLocationCoordinate2D(latitude: (latitude?.doubleValue)!, longitude: (longitude?.doubleValue)!), &self.itemPoint, UInt(self.itemPoint.count))
                                    if flag {//绿色
                                        self.greenArray.append(item)
                                    }else{//红色
                                        self.redArray.append(item)
                                    }
                                }else{
                                    
                                    self.greyArray.append(item)
                                }
                                
                            }else if (item.SignedResult?.rawValue ?? 0) == 1{
                                self.greyArray.append(item)
                            }
                        }
                        self.itemArray.append(contentsOf: self.greenArray)
                        self.itemArray.append(contentsOf: self.redArray)
                        self.itemArray.append(contentsOf: self.greyArray)
                        
                        //self.itemArray = Mapper<MWCurrentLocationModel>().mapArray(JSONArray: itemDic)
                        self.signCount!(self.itemArray.count)
                        print(self.itemArray)
                    }
                    
                    if self.itemArray.count == 0{
                        self.addEmptyDataView("暂无出勤数据")
                        return
                    }else{
                        self.removeEmptyView()
                    }
                    
                }
                self.tableView.reloadData()
                // callbackArr = Mapper<LCProjectListModel>().mapArray(JSONArray: itemDic)
                // completionHandler(WWValueResponse.init(value: callbackArr, success: true))
                //return
            }else{
                //WWProgressHUD.error("数据请求失败")
            }
            self.tableView.mj_header.endRefreshing()
        }
    }
    @objc func setupMWLocationData(){
        
        //发送现场页面刷新数据
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: XCRefreshNotification), object: nil)
        
        self.refreshRequest()
    }
    
}
extension LCSignViewController : UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.itemArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell  = tableView.dequeueReusableCell(withIdentifier: "sign") as! LCSignCell
        cell.checkButton.addTarget(self, action: #selector(checkTrackClick(_:)), for: .touchUpInside)
        cell.checkButton.tag = indexPath.row
        var flag = false
        var longitude = self.itemArray[indexPath.row].Location?.object(forKey: "Longitude") as? NSString
        var latitude = self.itemArray[indexPath.row].Location?.object(forKey: "Latitude") as? NSString
        if longitude != nil && latitude != nil && self.itemPoint.count > 0{
            flag = BMKPolygonContainsCoordinate(CLLocationCoordinate2D(latitude: (latitude?.doubleValue)!, longitude: (longitude?.doubleValue)!), &self.itemPoint, UInt(self.itemPoint.count))
            
        }
        cell.adressLabel.text = self.itemArray[indexPath.row].Location?.object(forKey: "Address") as? String ?? "暂无位置信息"
        print("\(longitude)----\(latitude)")
        //cell.setupDataWith(model: self.itemArray[indexPath.row],flag:flag)
        
        if indexPath.row < self.greenArray.count{
            cell.setCqListItem(model: self.itemArray[indexPath.row], _boardType: LCSignCell.BoardColor.Green)
        }else if indexPath.row < self.redArray.count && self.greyArray.count <= indexPath.row{
            cell.setCqListItem(model: self.itemArray[indexPath.row], _boardType: LCSignCell.BoardColor.Red)
        }else if indexPath.row < self.greyArray.count && self.redArray.count <= indexPath.row{
            cell.setCqListItem(model: self.itemArray[indexPath.row], _boardType: LCSignCell.BoardColor.Grey)
        }else{
            cell.setCqListItem(model: self.itemArray[indexPath.row], _boardType: LCSignCell.BoardColor.Grey)
        }
        
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 120
    }
    @objc private func checkTrackClick(_ tackButton : UIButton){
        /*let checkTrack = LCCheckTrackViewController(nibName: "LCCheckTrackViewController", bundle: nil)
        checkTrack.currentProject = self.selectedProject
        checkTrack.personInformation = self.itemArray[tackButton.tag]
        self.navigationController?.pushViewController(checkTrack, animated: true)*/
        
        let model:MWCurrentLocationModel = self.itemArray[tackButton.tag]
        var vc = WorkGuiJiControllerViewController(nibName: "WorkGuiJiControllerViewController", bundle: nil)
        //vc.MarketSupplyBaseID = self.MigrantWorkerID ?? ""
        vc.DemandBaseMigrantWorkerID = model.ID ?? ""
        vc.LocateTime = model.Location?.object(forKey: "LocateTime") as? String
        vc.MarketSupplyBaseID = selectedProject?.MarketSupplyBaseID
        vc.ProjectRange = self.itemPoint
        
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model:MWCurrentLocationModel = self.itemArray[indexPath.row]
        let mwDetail = MWDetailInfoViewController(nibName: "MWDetailInfoViewController", bundle: nil)
        mwDetail.DemandBaseMigrantWorkerID = model.ID
        mwDetail.currentProjectName = selectedProject?.ProjectName
        mwDetail.currentProjectId = selectedProject?.MarketSupplyBaseID
        mwDetail.isZG = true
        mwDetail.ProjectRange = self.itemPoint
        mwDetail.LocateTime = model.Location?.object(forKey: "LocateTime") as? String
        
        self.navigationController?.pushViewController(mwDetail, animated: true)
    }
}

extension LCSignViewController{
    func addEmptyDataView(_ status:String = "暂无数据"){
        self.tableView.isHidden = true
        self.emptylayout.isHidden = false
        self.emptylabel.text = status
    }
    func removeEmptyView(){
        self.tableView.isHidden = false
        self.emptylayout.isHidden = true
    }
}














